package com.lyf.network.practice.nio;

import org.junit.Test;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;

/**
 *
 *
 * @author LYF
 * @date 2022/6/24
 */
public class BufferTests {
    /*
    1.学习掌握Buffer的基础知识
    Channel  →  Buffer1..n  → Selector
    引入NIO的作用：非阻塞地进行通信--
    Buffer缓冲区

    主要理解 pos,limit,cap三个参数以及put,get的使用

     */
    @Test
    public void testBufferBase(){
        // Invariants: mark <= position <= limit <= capacity
        // Buffer的关键结构--- pos,limit,cap
//        private int mark = -1;
//        private int position = 0;
//        private int limit;
//        private int capacity;

        Buffer buffer1 = ByteBuffer.allocate(10);
        Buffer buffer2 = CharBuffer.allocate(10);

        ByteBuffer byteBuffer = (ByteBuffer) buffer1;
        byteBuffer.put("src".getBytes());// 将 scr放入buffer

        //byteBuffer.flip();
        // 此时pos =3, 需要调整pos
        byteBuffer.position(0);

        byte[] dst = new byte[10];
        ByteBuffer buffer = byteBuffer.get(dst,0,8);
        System.out.println(new String(dst)+":::"+byteBuffer.position());// pos = 8

        byteBuffer.position(0);
        byteBuffer.limit(4);// 设置上限，若不设置则会为cap--
        while(byteBuffer.hasRemaining()){
            byte bt = byteBuffer.get();
            System.out.println(bt+"::"+(char)bt);
        }

    }
}
